<?php
/**
 * Manage site common settings
 * @author Tuong Tran <tuong.tran@outlook.com>
 */
class SettingController extends Controller {
    public $activeMenu = 'setting';


    /**
     * site setting general
     */
    public function actionIndex($type = 'site') {
        if (Yii::app()->request->isPostRequest) {
            $settings = Yii::app()->settings;
            foreach ($_POST as $key => $value) {
                $settings->set($type, $key, $value);
            }

            Yii::app()->user->setFlash('success', 'Your settings has been updated');
            $this->refresh();
        }

        $settings = settings()->load($type);

        $this->render($type, array(
            'settings' => $settings
        ));
    }

    /**
     * clear cache both frontend and backend
     */
    public function actionDeleteCache() {
        if (Yii::app()->request->isPostRequest) {
            $this->_clearCache('frontend');
            $this->_clearCache('backend');
            Yii::app()->user->setFlash('success', 'Deleted all cache');
            $this->redirect(array('/default/index'));
        }

        $this->render('delete_cache');
    }

    private function _clearCache($where) {
        switch ($where) {
            case 'frontend':
                //Send Post Request to Frontend
                $timeout = 30;
                $curl = curl_init();
                $pvars = array('key' => FRONTEND_CLEAR_CACHE_KEY);
                curl_setopt($curl, CURLOPT_URL, FRONT_SITE_URL . '/site/caching');
                curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
                $result = curl_exec($curl);
                curl_close($curl);

                return $result == '0' ? false : true;
                break;
            case 'backend':
                Yii::app()->cache->flush();
                return true;
                break;
        }
    }

}